package com.neusoft.satoken.controller;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.util.SaResult;
import com.neusoft.satoken.util.CustomSaTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.Map;


/**
 * 认证相关
 */
@RestController
public class SaOAuth2ServerController {

    @Autowired
    CustomSaTokenUtil customSaTokenUtil;

    /**
     * 获取 access_token、refresh_token
     * @return
     */
    @RequestMapping("/oauth2/token")
    public Object getToken() {
        System.out.println("------- 进入请求: " + SaHolder.getRequest().getUrl());
        try {
            Map<String, Object> accessTokenAndRefreshToken = customSaTokenUtil.createAccessTokenAndRefreshToken();
            return SaResult.data(accessTokenAndRefreshToken);
        } catch (UnsupportedEncodingException e) {
            return SaResult.error(e.getMessage());
        }

    }

    /**
     * 刷新 access_token
     * @return
     */
    @RequestMapping("/oauth2/refresh")
    public Object refreshToken() {
        System.out.println("------- 进入请求: " + SaHolder.getRequest().getUrl());
        SaRequest request = SaHolder.getRequest();
        String accessToken = request.getParam("access_token");
        String reFreshToken = request.getParam("refresh_token");
        customSaTokenUtil.checkRefreshTokenValid(accessToken,reFreshToken);
        return getToken();
    }
}